#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <sys/select.h>
#include <unistd.h>

#include "../utils/command_analyse.h"
#include "../utils/command_parse.h"
#include "../utils/msg.h"
#include "../utils/password.h"
#include "../utils/train_trans.h"
#include "../utils/trans_file.h"
#include "client_event.h"
#include "connect_server.h"

void client_event(const int sockfd) {
  char username[512] = {0};
  char password[512] = {0};
  char encrypted_password[512] = {0};

  char output[1024] = {0};

  int recv_flag = RECV_MSG;

  printf("username: ");
  scanf("%s", username);
  send_msg(sockfd, username);
  printf("password: ");
  scanf("%s", password);

  int verify_flag = 1;
  while (verify_flag) {
    /* password_encrypt(username, password, encrypted_password); */
    send_msg(sockfd, password);
    bzero(output, sizeof(output));
    recv_msg(sockfd, output);
    printf("output = %s\n", output);
    if (strcmp(output, "welcome!") == 0) {
      verify_flag = 0;
    } else {
      printf("%s\n", output);
      printf("password: ");
      scanf("%s", password);
    }
  }

  fd_set rdset;

  char prefix[512];
  sprintf(prefix, "%s@ikun> ", username);

  printf("%s", prefix);
  fflush(stdout);
  while (1) {

    FD_ZERO(&rdset);
    FD_SET(STDIN_FILENO, &rdset);
    FD_SET(sockfd, &rdset);

    select(sockfd + 1, &rdset, NULL, NULL, NULL);

    if (FD_ISSET(STDIN_FILENO, &rdset)) {
      char command[1024] = {0};
      read(STDIN_FILENO, command, sizeof(command));
      int argc;
      char *argv[10];
      command_parse(command, &argc, argv);

      int command_type = command_analyse(argv[0]);

      if (!command_valid(command_type, argc)) {
        printf("invalid command!\n");
        printf("%s", prefix);
        fflush(stdout);
        continue;
      }
      if (command_type == COMMAND_QUIT) {
        printf("bye bye!\n");
        return;
      }
      if (command_type == COMMAND_GETS) {
        recv_flag = RECV_FILE;
        send_msg(sockfd, command);
        recv_file(sockfd, argv[1]);
        printf("%s", prefix);
        fflush(stdout);
      } else if (command_type == COMMAND_PUTS) {
        send_msg(sockfd, command);
        send_file(sockfd, argv[1], argv[1]);
        printf("%s", prefix);
        fflush(stdout);
      } else {
        recv_flag = RECV_MSG;
        send_msg(sockfd, command);
      }
    }

    if (FD_ISSET(sockfd, &rdset)) {
      if (recv_flag == RECV_MSG) {
        bzero(output, sizeof(output));
        int ret = recv_msg(sockfd, output);
        if (ret == 0) {
          break;
        }

        printf("%s\n", output);
      }
      /* } else if (recv_flag == RECV_FILE) { */
      /*   recv_file(sockfd); */
      /*   printf("done!\n"); */
      printf("%s", prefix);
      fflush(stdout);
    }
  }
}
